package com.dongdongkeji.base.common;

import com.socks.library.KLog;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * function description
 *
 * @author zhaiyong    2017/4/17
 * @version 1.0 <changes description>
 */

public class LoggingInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);


        /******************打印地址与参数**********************/
        KLog.d("url:" + request.url());
        KLog.d("method:" + request.method());

        if ("POST".equals(request.method())) {
            StringBuilder sb = new StringBuilder();
            if (request.body() instanceof FormBody) {
                FormBody body = (FormBody) request.body();
                for (int i = 0; i < body.size(); i++) {
                    sb.append(body.encodedName(i)).append("=").append(body.encodedValue(i)).append(",");
                }
                sb.delete(sb.length() - 1, sb.length());
                KLog.d("params:{ " + sb.toString() + " }");
            } else if (request.body() instanceof MultipartBody) {
                KLog.d("params:{ 文件/对象 }");
            }
        } else if ("GET".equals(request.method())) {
            String url = request.url().toString();
            if (url.contains("?")) {
                String temp = url.substring(url.indexOf("?") + 1);
                int num = temp.split("&").length;
                String divider = " , ";
                StringBuilder params = new StringBuilder();
                params.append("params:{");
                for (int i = 0; i < num; i++) {
                    params.append(temp.split("&")[i]).append(divider);
                }
                params.delete(params.length() - divider.length(), params.length());
                params.append("}");
                KLog.d(params.toString());

            } else {
                KLog.d("params:{ 没有请求的参数, 或地址有误 }");
            }
        }

        /*************************打印body方法 一   ****************************/
        /** 打印body， body不能直接打印，会将response给consume掉，因为它是一个流，只能用一次**/

//                ResponseBody responseBody = response.body();
//
//                // 得到responseBody后，分为两个部分来操作，source和mediaType
//
//                // 将source转为buffer
//                BufferedSource tempSource = responseBody.source();
//                tempSource.request(Long.MAX_VALUE);
//                Buffer tempBuffer = tempSource.buffer();
//
//                // 将mediaType转为charset
//                MediaType tempContent = responseBody.contentType();
//                Charset content = tempContent.charset(UTF8);
//
//                // 用buffer来读charset，最后显示出来
//                KLog.json(tempBuffer.clone().readString(content));

        /*************************打印body方法 二  ****************************/
        /**或者直接将response.body().string(), 然后再构建一个response将它还原**/
        MediaType contentType = response.body().contentType();
        String bodyString = response.body().string();

        KLog.json(bodyString);

        ResponseBody body = ResponseBody.create(contentType, bodyString);
        response = response.newBuilder().body(body).build();

        return response;
    }

    private boolean bodyEncoded(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
    }
}
